﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WTwitter.Model.Framework;
using WTwitter.Model.UserData;
using WTwitter.Model.Utility;

namespace WTwitter.Model.Twitter {
	/// <summary>
	/// Twitterの細かい挙動に対応したTimelineクラス
	/// </summary>
	class TwitterTimeline : Timeline {
		#region private member
		private IItemsReader _itemsReader;
		private readonly int _startupReadCount = 80;
		private long? sinceId;
		#endregion

		#region Constructor
		public TwitterTimeline(TimelineSetting setting, IItemsReader reader, AuthInfo info)
			: base(setting, reader, info) {
			_itemsReader = reader;
			_startupReadCount = setting.StartupReadCount;
		}

		public TwitterTimeline(TimelineSetting setting, IItemsReader reader)
			: this(setting, reader, null){
		}
		#endregion

		protected override void getItemsAsync(object sender, System.ComponentModel.DoWorkEventArgs e) {

			RequestParameter[] parameters;
			if (sinceId.HasValue) {
				parameters = new RequestParameter[] { new RequestParameter("since_id", sinceId.Value.ToString()) };
			} else {
				parameters = new RequestParameter[] { new RequestParameter("count", _startupReadCount.ToString()) };
			}

			try {
				using (var response = WebUtility.GetResponse(Url, "GET", parameters, AuthInfo))
				using (var stream = response.GetResponseStream()) {
					var result = _itemsReader.Read(stream);
					e.Result = result.ToList<ITimelineItem>();
				}
			} catch (Exception exeption) {
				e.Result = exeption;
			}
		}

		protected override void getItemsCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e) {
			var exception = e.Result as Exception;
			if (exception != null) {
				OnReadItems(new ReadTimelineEventArgs(exception));
				return;
			}

			var result = e.Result as List<ITimelineItem>;
			var newItems = new List<ITimelineItem>();
			foreach (var item in result) {
				if (!AllItems.Contains(item)) {
					newItems.Add(item);
					if (sinceId == null || item.Id > sinceId) {
						sinceId = item.Id;
					}
				}
			}
			OnReadItems(new ReadTimelineEventArgs(newItems));
		}
	}
}
